<template>
  <div class="home" style="background-color: #FFFFFF; padding: 20px;">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card>
          <div id="line" style="width: 100%; height: 400px; min-height: 400px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <div id="pie" style="width: 100%; height: 400px; min-height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-card>
          <div id="weekTrend" style="width: 100%; height: 400px; min-height: 400px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <div id="ratePie" style="width: 100%; height: 400px; min-height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import request from '@/utils/request'

export default {
  name: 'FeedbackStats',
  data() {
    return {
      chartData: {
        dates: [],
        approved: [],
        pending: [],
        rejected: [],
        pieData: [],
        weekData: [],
        rateData: []
      },
      lineChart: null,
      pieChart: null,
      weekChart: null,
      rateChart: null
    }
  },
  mounted() {
    this.loadData()
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    this.disposeCharts()
  },
  methods: {
    disposeCharts() {
      [this.lineChart, this.pieChart, this.weekChart, this.rateChart].forEach(chart => {
        chart && chart.dispose()
      })
    },

    handleResize() {
      [this.lineChart, this.pieChart, this.weekChart, this.rateChart].forEach(chart => {
        chart && chart.resize()
      })
    },

    async loadData() {
      try {
        const res = await request.get("/Shenhe/alldata")
        if (res?.code === "0") {
          this.processChartData(res.data)
          this.$nextTick(() => {
            this.initCharts()
          })
        }
      } catch (error) {
        console.error('数据加载失败:', error)
      }
    },

    processChartData(data) {
      // 重置数据
      this.chartData = {
        dates: [],
        approved: [],
        pending: [],
        rejected: [],
        pieData: [],
        weekData: [],
        rateData: []
      }

      const dateMap = {}
      const weekMap = {}
      const rateCount = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}

      // 处理数据
      data.forEach(item => {
        // 1. 处理状态数据
        if (!dateMap[item.date]) {
          dateMap[item.date] = { approved: 0, pending: 0, rejected: 0 }
        }

        switch(item.examine) {
          case '被采纳': dateMap[item.date].approved++; break
          case '待审核': dateMap[item.date].pending++; break
          case '未被采纳': dateMap[item.date].rejected++; break
        }

        // 2. 处理周数据（按星期分组）
        const date = new Date(item.date)
        const day = date.getDay() || 7 // 0-6转1-7（周一至周日）
        if (!weekMap[day]) {
          weekMap[day] = 0
        }
        weekMap[day]++

        // 3. 处理评分数据
        const rate = parseInt(item.rate) || 0
        if (rate >= 1 && rate <= 5) {
          rateCount[rate]++
        }
      })

      // 1. 状态图表数据
      this.chartData.dates = Object.keys(dateMap).sort((a, b) => new Date(a) - new Date(b))
      this.chartData.approved = this.chartData.dates.map(date => dateMap[date].approved)
      this.chartData.pending = this.chartData.dates.map(date => dateMap[date].pending)
      this.chartData.rejected = this.chartData.dates.map(date => dateMap[date].rejected)
      this.chartData.pieData = [
        { value: data.filter(i => i.examine === '被采纳').length, name: '被采纳' },
        { value: data.filter(i => i.examine === '待审核').length, name: '待审核' },
        { value: data.filter(i => i.examine === '未被采纳').length, name: '未被采纳' }
      ]

      // 2. 周趋势数据（按周一至周日排序）
      const weekDays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      this.chartData.weekData = weekDays.map((day, index) => {
        return weekMap[index + 1] || 0
      })

      // 3. 评分数据
      this.chartData.rateData = Object.keys(rateCount).map(rate => {
        return {
          value: rateCount[rate],
          name: `${rate}星`
        }
      })

      console.log('处理后的图表数据:', this.chartData)
    },

    initCharts() {
      this.initLineChart()
      this.initPieChart()
      this.initWeekTrendChart()
      this.initRatePieChart()
    },

    initLineChart() {
      const dom = document.getElementById('line')
      if (!dom) {
        console.error('折线图容器未找到')
        return
      }

      if (this.lineChart) {
        this.lineChart.dispose()
      }

      this.lineChart = echarts.init(dom)

      const option = {
        title: {
          text: '评价状态趋势',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: params => {
            let result = params[0].axisValue + '<br/>'
            params.forEach(item => {
              result += `${item.marker} ${item.seriesName}: ${item.value}<br/>`
            })
            return result
          }
        },
        legend: {
          data: ['被采纳', '待审核', '未被采纳'],
          bottom: 0
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.chartData.dates,
          axisLabel: {
            rotate: 30,
            formatter: value => value.split('-').slice(1).join('-')
          }
        },
        yAxis: {
          type: 'value',
          name: '评价数量'
        },
        series: [
          {
            name: '被采纳',
            type: 'line',
            data: this.chartData.approved,
            itemStyle: { color: '#67C23A' },
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            lineStyle: { width: 3 }
          },
          {
            name: '待审核',
            type: 'line',
            data: this.chartData.pending,
            itemStyle: { color: '#E6A23C' },
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            lineStyle: { width: 3 }
          },
          {
            name: '未被采纳',
            type: 'line',
            data: this.chartData.rejected,
            itemStyle: { color: '#F56C6C' },
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            lineStyle: { width: 3 }
          }
        ]
      }

      this.lineChart.setOption(option)
      console.log('状态趋势图已渲染')
    },

    initPieChart() {
      const dom = document.getElementById('pie')
      if (!dom) {
        console.error('饼图容器未找到')
        return
      }

      if (this.pieChart) {
        this.pieChart.dispose()
      }

      this.pieChart = echarts.init(dom)

      const option = {
        title: {
          text: '评价状态分布',
          subtext: `总评价数: ${this.chartData.pieData.reduce((sum, item) => sum + item.value, 0)}`,
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: this.chartData.pieData.map(item => item.name)
        },
        series: [
          {
            name: '评价状态',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              formatter: '{b}: {c} ({d}%)'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: true
            },
            data: this.chartData.pieData,
            color: ['#67C23A', '#E6A23C', '#F56C6C']
          }
        ]
      }

      this.pieChart.setOption(option)
      console.log('状态分布饼图已渲染')
    },

    initWeekTrendChart() {
      const dom = document.getElementById('weekTrend')
      if (!dom) {
        console.error('周趋势图容器未找到')
        return
      }

      this.weekChart = echarts.init(dom)

      const option = {
        title: {
          text: '一周反馈数量趋势',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>反馈数量: {c}'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
        },
        yAxis: {
          type: 'value',
          name: '反馈数量'
        },
        series: [{
          name: '反馈数量',
          type: 'line',
          data: this.chartData.weekData,
          smooth: true,
          itemStyle: {
            color: '#409EFF'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {offset: 0, color: 'rgba(64, 158, 255, 0.5)'},
              {offset: 1, color: 'rgba(64, 158, 255, 0.1)'}
            ])
          }
        }]
      }

      this.weekChart.setOption(option)
      console.log('周趋势图已渲染')
    },

    initRatePieChart() {
      const dom = document.getElementById('ratePie')
      if (!dom) {
        console.error('评分饼图容器未找到')
        return
      }

      this.rateChart = echarts.init(dom)

      const option = {
        title: {
          text: '评分占比分布',
          subtext: `总评价数: ${this.chartData.rateData.reduce((sum, item) => sum + item.value, 0)}`,
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: this.chartData.rateData.map(item => item.name)
        },
        series: [{
          name: '评分分布',
          type: 'pie',
          radius: '55%',
          center: ['50%', '50%'],
          data: this.chartData.rateData,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: true,
            formatter: '{b}: {c} ({d}%)'
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          color: ['#FF5A5F', '#FFB400', '#007A87', '#7B0051', '#00D1C1']
        }]
      }

      this.rateChart.setOption(option)
      console.log('评分饼图已渲染')
    }
  }
}
</script>
